package com.firewolf.hibernate.relationship.component.main;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.firewolf.hibernate.relationship.component.dto.Pay;
import com.firewolf.hibernate.relationship.component.dto.Worker;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;

	@Test
	public void testComponent() {
		openSession();

		Pay pay = new Pay(10000, 150000, 18);
		Worker w = new Worker();
		w.setName("liuxing");
		w.setPay(pay);
		session.save(w);

		closeSession();

	}

	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}

	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("component.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}
}
